/**
 * 
 */
package br.com.CSH4RK.componenteCRUD.modelo.service;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import br.com.CSH4RK.componenteCRUD.modelo.modelo.ModeloBase;

/**
 * @author Csh4rk
 * 
 */
@Transactional
public abstract class ServicoBaseDefault<T extends ModeloBase<?>> implements
		ServicoBase<T> {

	@PersistenceContext
	protected EntityManager entityManager;

	@Transactional(readOnly = false)
	public void save(T entidade) {
		Object id = entidade.getId();

		if (id == null) {
			entityManager.persist(entidade);
		} else {
			entityManager.merge(entidade);
		}
	}

	@Transactional(readOnly = false)
	public void delete(Object id) throws EntityNotFoundException {
		entityManager.remove(this.getById(id));
	}

	@Transactional
	public T getById(Object id) throws EntityNotFoundException {

		T entidade = entityManager.find(this.getClassT(), id);

		if (entidade == null) {
			throw new EntityNotFoundException();
		} else {
			return entidade;
		}
	}

	@SuppressWarnings("unchecked")
	private Class<T> getClassT() {

		Type type = getClass().getGenericSuperclass();

		if (type instanceof ParameterizedType) {

			ParameterizedType parameterizedType = (ParameterizedType) type;

			Class<T> tClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];

			return tClass;
		} else
			return null;
	}

}
